package net.taviscaron.drivenotes.android.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import net.taviscaron.drivenotes.android.Constants;
import net.taviscaron.drivenotes.android.R;

public class MainActivity extends Activity {
    private static final String LOGIN_ACTION = "net.taviscaron.drivenotes.android.LOGIN";
    private static final String GARAGE_ACTION = "net.taviscaron.drivenotes.android.GARAGE";
    private static final String NOTES_ACTION = "net.taviscaron.drivenotes.android.NOTES";
    private static final String PLACES_ACTION = "net.taviscaron.drivenotes.android.PLACES";

    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        checkLogin();
        
        setContentView(R.layout.main);
        
        ((Button)findViewById(R.id.garageButton)).setOnClickListener(new OnClickListener() {
	    public void onClick(View arg0) {
		garageButtonClick();
	    }
	});

        ((Button)findViewById(R.id.notesButton)).setOnClickListener(new OnClickListener() {
	    public void onClick(View arg0) {
		notesButtonClick();
	    }
	});
        
        ((Button)findViewById(R.id.placesButton)).setOnClickListener(new OnClickListener() {
	    public void onClick(View arg0) {
		placesButtonClick();
	    }
	});
        
        ((Button)findViewById(R.id.logoutButton)).setOnClickListener(new OnClickListener() {
	    public void onClick(View arg0) {
		logoutButtonClick();
	    }
	});
    }

    @Override
    protected void onStart() {
	super.onStart();
	checkLogin();
    }
    
    private void checkLogin() {
        SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);
        String authKey = preferenceManager.getString(Constants.AUTH_KEY_PROP_KEY, null);
        
        if(authKey == null || authKey.trim().length() == 0) {
            goLogin();
        }
    }
    
    private void garageButtonClick() {
	startActivity(new Intent(GARAGE_ACTION));
    }

    private void notesButtonClick() {
	startActivity(new Intent(NOTES_ACTION));
    }
    
    private void placesButtonClick() {
	startActivity(new Intent(PLACES_ACTION));
    }
    
    private void goLogin() {
        startActivity(new Intent(LOGIN_ACTION));
        finish();
    }
    
    private void logoutButtonClick() {
	// TODO: logout from server!
	SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);
	preferenceManager.edit().remove(Constants.AUTH_KEY_PROP_KEY).commit();
	goLogin();
    }
}
